package top.system.dept.utils;

import com.fasterxml.jackson.annotation.JsonIgnore;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: MailUtil
 * @Author: Amosen
 * @Since: 2021/5/30
 */
public class MapUtil {

    // 将对象封装为map对象
    public static Map<String, Object> obj2Map(Object obj) {
        Class<?> objClass = obj.getClass();
        Field[] declaredFields = objClass.getDeclaredFields();
        Map<String, Object> returnMap = new HashMap<>();
        for (Field declaredField : declaredFields) {
            try {
                declaredField.setAccessible(true);
                // 增加对JsonIgnore注解的支持，使用JsonIgnore注解控制数据对用户的展示
                if (declaredField.getAnnotation(JsonIgnore.class) != null) {
                    continue;
                }
                returnMap.put(declaredField.getName(), declaredField.get(obj));
            } catch (IllegalAccessException e) {
                returnMap.put(declaredField.getName(), null);
            }
        }
        return returnMap;
    }

    // 将map对象转化为指定的对象
    public static Object map2Obj(Map<String, Object> map, Class clazz) {
        try {
            Object newInstance = clazz.newInstance();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                try {
                    Field declaredField = clazz.getDeclaredField(entry.getKey());
                    declaredField.setAccessible(true);
                    declaredField.set(newInstance, entry.getValue());
                } catch (NoSuchFieldException e) {
                    throw new RuntimeException("The field with name <" + entry.getKey() + "> does not exists.");
                }
            }
            return newInstance;
        } catch (InstantiationException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

}
